package com.baway.biliclitent.fragment;

import android.content.Context;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.baway.biliclitent.R;
import com.baway.biliclitent.adapter.RecommendAdapter;
import com.baway.biliclitent.model.RecommendBanner;
import com.baway.biliclitent.model.RecommendBean;
import com.baway.biliclitent.util.OkHttpUtils;
import com.baway.biliclitent.util.SnackbarUtil;
import com.baway.biliclitent.view.CustomEmptyView;

import java.util.ArrayList;
import java.util.List;

/**
 * 推荐 Fragment
 */

public class FragmentRecommend extends Fragment {

    private SwipeRefreshLayout mSwipe_refresh_layout;
    private RecyclerView mRecycle;
    private CustomEmptyView mEmpty_layout;
    private List<String> mImages;
    private View mView;

    
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_recommend, container, false);
       
        return mView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initview();
        boolean networkAvailable = isNetworkAvailable(getActivity());
        if (networkAvailable) {
            initData();
        }else
        {
            initEmptyView();
        }


    }

    private void initview() {
        mSwipe_refresh_layout = (SwipeRefreshLayout) mView.findViewById(R.id.swipe_refresh_layout);
        mRecycle = (RecyclerView) mView.findViewById(R.id.recycle);
        mEmpty_layout = (CustomEmptyView)mView.findViewById(R.id.empty_layout);
        mSwipe_refresh_layout.setProgressBackgroundColorSchemeColor(Color.parseColor("#fb7299"));
        mSwipe_refresh_layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mSwipe_refresh_layout.setRefreshing(false);
                    }
                },200);
            }
        });
    }

    private void initData() {

        OkHttpUtils httpUtils = OkHttpUtils.getHttpUtils();
        httpUtils.loadDataFromNet("http://app.bilibili.com/x/banner?plat=4&build=411007&channel=bilih5", RecommendBanner.class, new OkHttpUtils.CallBackListener<RecommendBanner>() {



            @Override
            public void onSuccess(RecommendBanner result) {
                mImages = new ArrayList<>();
                List<RecommendBanner.DataBean> data = result.getData();
                if (data != null) {
                    for (int i = 0; i < data.size(); i++) {
                        mImages.add(data.get(i).getImage());
                    }
                } else {
                    return;
                }

            }

            @Override
            public void onFail() {

            }
        });

        httpUtils.loadDataFromNet("http://app.bilibili.com/x/show/old?platform=android&device=&build=412001", RecommendBean.class, new OkHttpUtils.CallBackListener<RecommendBean>() {

            @Override
            public void onSuccess(RecommendBean result) {
                List<RecommendBean.ResultBean> result1 = result.getResult();
                mRecycle.setLayoutManager(new LinearLayoutManager(getActivity()));
                RecommendAdapter recommendAdapter=new RecommendAdapter(getActivity(), result1,mImages);
                mRecycle.setAdapter(recommendAdapter);
            }

            @Override
            public void onFail() {

            }
        });



    }


    // 加载失败视图

    public void initEmptyView() {

        mSwipe_refresh_layout.setRefreshing(false);
        mEmpty_layout.setVisibility(View.VISIBLE);
        mRecycle.setVisibility(View.GONE);
        mEmpty_layout.setEmptyImage(R.drawable.img_tips_error_load_error);
        mEmpty_layout.setEmptyText("加载失败~(≧▽≦)~啦啦啦.");
        SnackbarUtil.showMessage(mRecycle, "数据加载失败,请重新加载或者检查网络是否链接");
    }

    //成功调用
    public void hideEmptyView() {

        mEmpty_layout.setVisibility(View.GONE);
        mRecycle.setVisibility(View.VISIBLE);
    }

    /**
     * 检测当的网络（WLAN、3G/2G）状态 
     * @param context Context 
     * @return true 表示网络可用 
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null && info.isConnected())
            {
                // 当前网络是连接的  
                if (info.getState() == NetworkInfo.State.CONNECTED)
                {
                    // 当前所连接的网络可用  
                    return true;
                }
            }
        }
        return false;
    }
}
